import React from 'react'
import PropTypes from 'prop-types'
import { Form, Row, Col, Cascader, Input, InputNumber, Button, Tooltip, Space } from 'antd'
import { MinusOutlined } from '@ant-design/icons'
import style from './block.module.less'
import { CaseContext } from '../context'
import itemStyle from './ClaimItem.module.less'
import { normalStatusList } from '@js/config'
const { Item } = Form
const { TextArea } = Input
const columnMap = {
  label: 'title',
  value: 'title'
}

// 改变请求类型
function changeTypes (options, index, configs, callback) {
  const len = options.length
  const result = [...configs]
  let rules = []
  if (len > 0) {
    rules = [...options[len - 1].json_rule]
  }
  result.splice(index, 1, rules)
  callback(result, index, rules)
}

// 删除按钮
function RemoveBtn ({ deleleAble, remove, field }) {
  if (!deleleAble) {
    return null
  }
  return (
    <Col span={1}>
      <span className={itemStyle['del-btn']}>
        <Button shape='circle' size='small' icon={<MinusOutlined />} onClick={() => remove()} />
      </span>
    </Col>
  )
}

// 获取数字中文单位
function getCnUnit (v) {
  const list = ['个', '十', '百', '千', '万', '十万', '百万', '千万', '亿', '十亿', '百亿', '千亿', '兆', '十兆', '百兆', '千兆']
  if (!v) {
    return list[0]
  }
  const money = String(Math.floor(v))
  return list[money.length - 1]
}

// 金钱输入框
function MoneyInput ({ value, placeholder, onChange, config, disabled }) {
  const input = (
    <div className={itemStyle['money-input']}>
      <InputNumber
        value={value}
        className={itemStyle['number-input']}
        placeholder={placeholder}
        maxLength={16}
        disabled={disabled}
        min={0}
        onChange={v => {
          onChange(v)
        }}
      />
      <span className={itemStyle['money-unit']}>{getCnUnit(value)}</span>
    </div>
  )
  if (config.placeholder) {
    return (
      <Tooltip title={config.placeholder} placement='topLeft' trigger='focus'>
        {input}
      </Tooltip>
    )
  }
  return input
}

// 渲染费用输入列表
function renderFeeInputList (field, disabled, list, changeClaim) {
  return list.map((li, i) => (
    <Row key={i}>
      <Col span={6} />
      <Col span={10}>
        <Item label={li.title} name={[field.name, li.key]} rules={[{ required: true, message: `${li.title}不能为空` }]}>
          <MoneyInput className={itemStyle['number-input']} placeholder={`请输入${li.title}`} disabled={disabled} config={li} onChange={() => changeClaim()} />
        </Item>
      </Col>
    </Row>
  ))
}

function Main ({ field, index, len, remove, deleleAble }) {
  const isFirst = index === 0
  return (
    <CaseContext.Consumer>
      {({ claimItemConfig, claimItemFeeConfig, disabled, isModify, caseDetail, originClaim, setClaimItemFeeConfig, removeClaimItemFeeConfing, statisticDisputeAmount, changeProcedure, changeFeeType, computeFee, setOriginClaim, cancelSplitClaim, setOriginClaimVisible }) => {
        const feeRule = claimItemFeeConfig[index] || []
        function changeClaim () {
          statisticDisputeAmount()
          changeProcedure()
          changeFeeType()
          computeFee()
        }
        function removeHandle () {
          remove(field.name)
          removeClaimItemFeeConfing(index)
          setTimeout(() => {
            changeClaim()
          }, 0)
        }
        const splitBtnVisible = isFirst && len === 1 && !originClaim && normalStatusList.indexOf(caseDetail.status) === -1
        const cancelSplitBtnVisible = isFirst && originClaim
        return (
          <>
            <Row>
              {
                isFirst ? (
                  <>
                    <Col span={4} className={style['block-title']}><span>仲裁请求</span></Col>
                    <Col span={2} className={style['block-title']}>
                      <span className={style['order-no']}>{index + 1}</span>
                    </Col>
                  </>
                ) : (
                  <Col span={6} className={style['block-title']}>
                    <span className={style['order-no']}>{index + 1}</span>
                  </Col>
                )
              }
              <Col span={10}>
                <Item label='仲裁请求' name={[field.name, 'desc']} style={{ marginBottom: 12 }}>
                  <TextArea placeholder='请输入仲裁请求' autoSize={{ minRows: 2 }} disabled={disabled} />
                </Item>
              </Col>
              {!disabled && !isModify ? <RemoveBtn deleleAble={deleleAble} remove={() => removeHandle()} field={field} /> : <Col span={1} />}
              {
                splitBtnVisible ? (
                  <Button type='link' className={style['split-btn']} onClick={setOriginClaim}>智能分项</Button>
                ) : null
              }
              {
                cancelSplitBtnVisible ? (
                  <Col span={3}>
                    <Space>
                      <Button type='link' className={style['split-btn']} onClick={cancelSplitClaim}>取消分项</Button>
                      <Button type='link' className={style['split-btn']} onClick={() => setOriginClaimVisible(true)}>原请求</Button>
                    </Space>
                  </Col>
                ) : null
              }
            </Row>
            <Row>
              <Col span={6} />
              <Col span={10}>
                <Item label='请求类型' name={[field.name, 'type']} rules={[{ required: true, message: '请求项类型不能为空' }]}>
                  <Cascader options={claimItemConfig} fieldNames={columnMap} disabled={disabled || isModify} onChange={(labels, options) => changeTypes(options, index, claimItemFeeConfig, setClaimItemFeeConfig)} />
                </Item>
              </Col>
            </Row>
            {renderFeeInputList(field, disabled || isModify, feeRule, changeClaim)}
          </>
        )
      }}
    </CaseContext.Consumer>
  )
}

Main.propTypes = {
  field: PropTypes.object,
  index: PropTypes.number,
  len: PropTypes.number,
  remove: PropTypes.func,
  deleleAble: PropTypes.bool
}

Main.defaultProps = {
  field: {},
  index: -1,
  len: 0,
  remove: () => {},
  deleleAble: false
}

export default Main
